
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:proj_sfv/component/MyVideoPlayer.dart';
import 'package:proj_sfv/domain/Video.dart';
import 'package:proj_sfv/http/api.dart';
import 'package:proj_sfv/http/requests.dart';
import 'package:proj_sfv/store/MyAppState.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

/// 首页页面
class VideoPage extends StatefulWidget {
  const VideoPage();
  @override
  State<VideoPage> createState() => _VideoPageState();
}

class _VideoPageState extends State<VideoPage> with AutomaticKeepAliveClientMixin {
   Video video;
   Future<http.Response> resp;
   List<Video> videos = [];
   int _currentIndex = 0;
   String token;
   int id;
   PageController _controller;
   void initVideo() {
    resp.then((value)
     {
       var videosData = jsonDecode(utf8.decode(value.body.codeUnits))['data'] as List<dynamic>;
        for (var element in videosData) {
          videos.add(Video.fromJson(element));
        }
       setState(() {
          video = videos[0];
       });
     });
   }

  @override
  void initState() {
     _controller = PageController(initialPage: _currentIndex,);
    super.initState();
    /**
     * 请求获取视频信息
     */
    SharedPreferences.getInstance().then((value) async {
      token = value.getString('token') ?? "";
      id = value.getInt("id") ?? "";
      var resp = await getRandomVideosRequest(context, token, id);
      List<int> ids = [];
      for (var element in resp) { ids.add(element.authorId);}
      var resp2 = await getUserProfileRangeRequest(context, ids, token);
      if (resp2 != null) {
        for (int i = 0; i < resp.length; ++i) {
          resp[i].userVo = resp2[resp[i].authorId];
        }
      }
      setState(() {
        videos = resp;
      });
    });

  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StoreConnector<MyAppState, MyAppState>(
        converter: (store) => store.state,
        builder: (context, state) {
          return StoreConnector<MyAppState, dynamic>(
              converter: (store) {
                return store;
              },
              builder: (context, store) {
                return Scaffold(
                    body: WillPopScope(
                      onWillPop: () async {
                        return false;
                      },
                      child: PageView.builder(
                        itemCount: videos.length,
                        scrollDirection: Axis.vertical,
                        onPageChanged: (index)  {
                          if (index >= videos.length - 2) {
                            getRandomVideosRequest(context, token, id).then((value) async {
                              List<int> ids = [];
                              for (var element in value) { ids.add(element.authorId);}
                              var resp2 = await getUserProfileRangeRequest(context, ids, token);
                              if (resp2 != null) {
                                for (int i = 0; i < value.length; ++i) {
                                  value[i].userVo = resp2[value[i].authorId];
                                }
                              }
                              setState(() {
                                videos.addAll(value);
                                _currentIndex = index;
                              });
                            });
                          }
                        },
                        itemBuilder: (context, index)  {
                          return TweenAnimationBuilder(tween: Tween(begin: 0, end: 1.0),
                              duration: Duration(microseconds: 500),
                              curve: Curves.easeInOut,
                              builder: (context, value, child) {
                                  return Transform.translate(
                                      offset: Offset(0, 0),
                                      child: child,
                                  );
                              },
                            child: MyVideoPlayer(videos[index], token, id, state),
                          );
                        },
                        controller: _controller,

                      ),
                    )
                );
              }
          );
        }
    );
  }

  @override
  bool get wantKeepAlive => true;
}